package server

import (
	"context"
	"errors"
	"fmt"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/const"
	time2 "longmen/server/pkg/common/helper/timehelper"
	"longmen/server/pkg/db/mysql"
	pb "longmen/server/pkg/protobuf"
	"time"
)

func (s *Server) Deactive(ctx context.Context, req *pb.DeactiveReq) (*pb.DeactiveResp, error) {
	user, err := mysql.GetUserParam(map[string]interface{}{"id": req.Uid})
	if err != nil || user.Id == 0 {
		return nil, errors.New("uid not found")
	}
	if err != nil {
		return nil, err
	}
	if req.Recall == 0 {
		//err = cache.SetUserToken(int(req.Uid), util.TOKEN_GOOD_BYE)//先不登出
		if err != nil {
			global.Log.Errorf("6Deactive9:%v", err)
		}
		if user.Status == _const.ACCOUNT_DEACTIVED {
			return nil, fmt.Errorf("已申请过注销")
		}
		user.Status = _const.ACCOUNT_DEACTIVED
		user.OnlineStatus = 9
		user.DeactiveTime = time.Now().Add(24 * 5 * time.Hour)
		if err := mysql.UpdateXAnyParam(nil, []string{"status", "online_status", "deactive_time"}, user, "Deactive"); err != nil {
			return nil, err
		}
		//return &pb.DeactiveResp{Msg: fmt.Sprintf("%d, every new beginning comes from some other beginning's end.", req.Uid)}, nil
		return &pb.DeactiveResp{Msg: user.DeactiveTime.Local().Format(time2.TIME_LAYOUT_FORMAT_1)}, nil
	} else {
		if user.Status != _const.ACCOUNT_DEACTIVED {
			return nil, fmt.Errorf("未申请过注销")
		}
		user.Status = _const.ACCOUNT_STATUS_NORMAL
		if err := mysql.UpdateXAnyParam(nil, []string{"status"}, user, "Deactive"); err != nil {
			return nil, err
		}
		return &pb.DeactiveResp{Msg: fmt.Sprintf("%d, welcome back.", req.Uid)}, nil
	}

}
